package com.gaofans.vertx.boot.web.cors;

import com.gaofans.vertx.boot.web.route.RouterExtConfigurer;
import com.gaofans.vertx.boot.web.utils.HttpHandlerOrder;
import com.gaofans.vertx.boot.web.utils.WebConstant;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.handler.CorsHandler;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author GaoFans
 */
@Configuration(proxyBeanMethods = false)
public class CorsHandlerAutoConfig {

    @Bean
    @ConfigurationProperties(prefix = WebConstant.VERTX_WEB_CORS_PREFIX)
    public CorsHandlerProperties corsHandlerProperties(){
        return new CorsHandlerProperties();
    }

    @Bean
    public RouterExtConfigurer corsHandlerConfigurer(CorsHandlerProperties properties){
        return router -> {
            Route route = router.route().order(HttpHandlerOrder.CORS_HANDLER);
            for (String s : properties.getPath()) {
                route.path(s);
            }
            route.handler(CorsHandler
                    .create(properties.getAllowedOriginPattern())
                    .allowedHeaders(properties.getAllowedHeaders())
                    .allowCredentials(properties.isAllowCredentials())
                    .allowedMethods(properties.getAllowedMethods())
                    .exposedHeaders(properties.getExposedHeaders())
                    .maxAgeSeconds(properties.getMaxAgeSeconds()));
        };
    }
}
